﻿using System;
using System.Collections.Generic;
using System.Text;

namespace RedBlueBalls
{
    /// <summary>
    /// Calculate the sum of red balls
    /// </summary>
    class RedSum
    {
        private static bool analyzed = false;
        private static int DEPTH = 20;
        private static List<int> sumList = new List<int>();
        private static int lowerVal;
        private static int upperVal;
        private static int[] lastSums = new int[DEPTH];

        public static void analyze(RedBlueBallRecord[] records)
        {
            sumList.Clear();
            foreach (RedBlueBallRecord record in records)
            {
                int sum = record.GetSumRed();
                Util.Add(sumList, sum);
            }

            int index = sumList.Count / 3;
            upperVal = sumList[index];
            lowerVal = sumList[sumList.Count - 1 - index];
            Tracer.AppendMessage(String.Format("Lower {0}, Upper {1}", lowerVal, upperVal));

            // Show last 20 records
            for (int i = 0; i < DEPTH; i++)
            {
                lastSums[i] = records[records.Length - 1 - i].GetSumRed();
                Tracer.AppendMessage(String.Format("Last {0}: {1}", (i+1).ToString("2D"), lastSums[i]));
            }

            analyzed = true;
        }

        public static bool predict(RedBlueBallRecord candidate)
        {
            if (!analyzed)
            {
                Tracer.AppendMessage("Please analyze the data first!");
                return false;
            }

            int sum = candidate.GetSumRed();

            for (int i = 0; i < DEPTH; i++)
            {
                if (sum == lastSums[i])
                    return false;
            }

            // No segment overlap
            if (lastSums[0] < lowerVal && sum > upperVal)
                return false;
            if (lastSums[0] > upperVal && sum < lowerVal)
                return false;

            // No linear sum
            if (sum == lastSums[0] * 2 - lastSums[1])
                return false;

            return true;
        }
    }
}
